package grape.wx.service.mp.impl.handler;

import grape.wx.service.mp.MpProperties;
import grape.wx.service.mp.api.handler.IMpSubscribeHandler;
import grape.wx.service.mp.user.api.IMpUserService;
import grape.wx.service.mp.user.po.MpUser;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 关注处理
 * Created by yangwei
 * Created at 2020/7/21 18:43
 */
@Service
public class MpSubscribeHandlerImpl implements IMpSubscribeHandler {

    @Autowired
    private IMpUserService iMpUserService;
    @Autowired
    private MpProperties mpProperties;
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {

        MpProperties.MpConfig mpConfig = mpProperties.abtainConfigByAppCodeOrAppId(WxMpConfigStorageHolder.get());
        // 用户关注添加用户信息
        MpUser mpUser = iMpUserService.getByOpenidAndAppCode(wxMessage.getFromUser(), mpConfig.getAppCode());
        // 如果存在只更新关注状态
        if (mpUser != null) {
            if(mpUser.getIsSubscribe() == null || !mpUser.getIsSubscribe()){
                MpUser mpUserForUpdate = new MpUser();
                mpUserForUpdate.setId(mpUser.getId());
                mpUserForUpdate.setIsSubscribe(true);
                WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
                iMpUserService.updateById(wxMpUser,mpConfig,mpUser);
            }
        }
        // 如果不存在
        else {
            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
            iMpUserService.insert( wxMpUser, mpConfig, MpUser.DictHowFrom.valueOf(wxMpUser.getSubscribeScene()));

        }
        return null;
    }
}
